package com.manbas.zhg.manbas.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/16.
 */

public class HttpUtis {
    private static String PATH;
    private static URL url;
    static StringBuilder response;

    public HttpUtis(){
        super();
    }



    public static String sendPostMessage(Map<String,String> params,String encode,String path){
        try {
            url=new URL(PATH);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder=new StringBuilder();
        if(params!=null&&!params.isEmpty()){
            for(Map.Entry<String,String>entry : params.entrySet()){
                try {
                    stringBuilder.append(entry.getKey())
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(),encode))
                            .append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
            try {
                HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(3000);
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoInput(true);//读取数据
                urlConnection.setDoOutput(true);//向服务器写数据
                //获取上传信息的大小和长度
                byte[] myData=stringBuilder.toString().getBytes();
                //设置请求体的类型是文本类型，表示当前提交的是文本数据
                urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                urlConnection.setRequestProperty("Content-Length",String.valueOf(myData.length));
                //获得输出流，像服务器输出内容
                OutputStream outputStream=urlConnection.getOutputStream();
                //写入数据
                outputStream.write(myData,0,myData.length);
                outputStream.close();
                int responseCode=urlConnection.getResponseCode();
                if(responseCode==200){
                    //取回响应的结果
                    return changeInputStream(urlConnection.getInputStream(),encode);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  "";
    }
    private static String changeInputStream(InputStream inputStream,String encode){
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        byte[] data=new byte[1024];
        int len=0;
        String result=null;
        if(inputStream!=null){
            try {
                while((len=inputStream.read(data))!=-1){
                    byteArrayOutputStream.write(data,0,len);
                }
                result=new String(byteArrayOutputStream.toByteArray(),encode);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }
    public static String api( String path,Map<String,String> params){
        String encode="utf-8";
        StringBuilder stringBuilder=new StringBuilder();
        for(Map.Entry<String,String>entry : params.entrySet()){
            try {
                stringBuilder.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(),encode))
                        .append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        path=path+"?"+stringBuilder.toString();
        LogUtil.Log(path);
        final String finalPath = path;
        new Thread(){
            @Override
            public void run() {
                super.run();
                invokeApi(finalPath);
            }
        }.start();
        return response+"";

    }

    public static void invokeApi(String path) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(path);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            LogUtil.Log(response.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
